package client;

import client.bean.ServerInfo;

import java.io.IOException;

public class Client {
    private static boolean done;

    public static void main(String[] args) {
        ServerInfo info = UDPSearcher.searchServer(10000);
        System.out.println("Server:" + info);

        if (info == null) {
            return;
        }

        // 当前的连接数据
        int size = 0;
        List<TCPClient> tcpClients = new ArrayList<>();
        for (int i=0; i<1000; i++) {
            try {
                TCPClient tcpClient = TCPClient.startWith(info);
                if (tcpClient == null) {
                    System.out.println("连接异常");
                    continue;
                }

                tcpClients.add(tcpClient);
                System.out.println("连接成功："+ (++size));
            } catch (Exception exception) {
                System.out.println("连接异常");
            }


            try {
                // 因为服务器只能同时维持50个连接
                Thread.sleep(20);
            } catch (Exception exception) {
                exception.printStackTrace();
            }

            System.in.read();

            Runnable runnable = () -> {
                @Override
                public void run() {
                    while (!done) {
                        for (TCPClient tcpClient:tcpClients) {
                            tcpClient.send("Hello--")
                        }

                        try {
                            // 因为服务器只能同时维持50个连接
                            Thread.sleep(1000);
                        } catch (Exception exception) {
                            exception.printStackTrace();
                        }
                    }
                }
            }
            Thread thread = new Thread(runnable);
            thread.start();

            System.in.read();
            done = true;
            try {
                // 等待线程执行完成
                Thread.join();
            } catch (Exception exception) {
                exception.printStackTrace();
            }

            // 客户端结束操作
            for (TCPClient tcpClient:tcpClients) {
                tcpClient.exit();
            }
        }
    }
}
